<template>
  <div class="chart-container">
    <!-- 筛选条件区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <h2>员工销售额报表</h2>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateChange"
          />
        </el-col>
        <el-col :span="6">
          <el-select v-model="vehicleModel" placeholder="请选择主要销售类型" clearable @change="handleFilter">
            <el-option
              v-for="item in modelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleFilter">查询</el-button>
<!--          <el-button type="success" @click="handleExport">导出</el-button>-->
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="data-item">
            <div class="data-title">总销售额</div>
            <div class="data-value">¥{{ totalSales }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="data-item">
            <div class="data-title">订单总数</div>
            <div class="data-value">{{ totalOrders }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="data-item">
            <div class="data-title">平均订单金额</div>
            <div class="data-value">¥{{ averageOrderAmount }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 销售趋势图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>销售趋势分析</span>
          </div>
          <div ref="trendChart" class="chart"></div>
        </el-card>
      </el-col>
      <!-- 销售排名图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>销售排名</span>
          </div>
          <div ref="rankChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getSaleChatData } from '@/api/chat/chat'

export default {
  name: "saleChart",
  data() {
    return {
      dateRange: [], // 日期范围
      vehicleModel: '', // 选中的车型
      modelOptions: [], // 销售汽车类型
      loading: false,
      trendChart: null, // 销售趋势图实例
      rankChart: null, // 销售排名图实例
      chartData: {
        trend: [], // 趋势数据
        rank: [] // 排名数据
      }
    }
  },
  computed: {
    // 计算总销售额
    totalSales() {
      return this.chartData.trend.reduce((sum, item) => sum + Number(item.sales_volume), 0).toFixed(2)
    },
    // 计算订单总数
    totalOrders() {
      return this.chartData.trend.length
    },
    // 计算平均订单金额
    averageOrderAmount() {
      return (this.totalSales / (this.totalOrders || 1)).toFixed(2)
    }
  },
  mounted() {
    this.initCharts()
    this.fetchChartData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.trendChart && this.trendChart.dispose()
    this.rankChart && this.rankChart.dispose()
  },
  methods: {
    // 初始化图表
    initCharts() {
      this.trendChart = echarts.init(this.$refs.trendChart)
      this.rankChart = echarts.init(this.$refs.rankChart)
    },

    // 处理日期变化
    handleDateChange() {
      this.handleFilter()
    },

    // 处理筛选
    handleFilter() {
      this.fetchChartData()
    },

    // 处理导出
    handleExport() {
      // 实现导出逻辑
    },

    // 获取图表数据
     fetchChartData() {
       console.log(this.dateRange)


      let data = {
        vehicleModel: this.vehicleModel
      }
       if(this.dateRange){
         data.startDate = this.dateRange[0]
         data.endDate = this.dateRange[1]
       }
      getSaleChatData(data).then(res => {
        this.chartData.trend = res.data
        // 数组深拷贝
        let tempRes = res.data.map(item => JSON.parse(JSON.stringify(item)));
        //计算排名
        tempRes.sort((a, b) => b.sales_volume - a.sales_volume);

        // 添加排名属性
        tempRes.forEach((item, index) => {
          item.rank = index + 1; // 排名从1开始
        });

        this.chartData.rank = tempRes

        //销售汽车类型
        this.modelOptions = res.data.map(item => { return {"value":item.sale_type,"label":item.sale_type}})
        this.updateCharts()
      }).catch(err => {
        console.log(err)
        this.$message.error('获取数据失败')
      })
    },

    // 更新图表
    // 更新图表方法的修改
    updateCharts() {
      // 更新销售趋势图
      this.trendChart.setOption({
        title: { text: '销售趋势分析' },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `日期：${params[0].axisValue}<br/>
                    销售额：￥${params[0].value}<br/>
                    客户：${params[1].value}`
          }
        },
        legend: {
          data: ['销售额']
        },
        grid: {
          left: '3%',
          right: '8%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chartData.trend.map(item => item.sale_begin_data),
          axisLabel: {
            rotate: 30
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额(元)',
            position: 'left',
            axisLabel: {
              formatter: '{value} 元'
            }
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            smooth: true,
            areaStyle: {
              opacity: 0.3
            },
            data: this.chartData.trend.map(item => item.sales_volume),
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '客户信息',
            type: 'scatter',
            symbolSize: 10,
            data: this.chartData.trend.map(item => item.employee_name),
            label: {
              show: true,
              position: 'top',
              formatter: function(params) {
                const index = params.dataIndex;
                return this.chartData.trend[index].employee_name;
              }.bind(this)
            }
          }
        ]
      })
    
      // 更新销售排名图
      this.rankChart.setOption({
        title: { text: '销售排名统计' },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: function(params) {
            return `员工：${params[0].name}<br/>
                    销售额：￥${params[0].value}<br/>
                    排名：第${params[0].dataIndex + 1}名`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            dataView: { readOnly: false },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'value',
          name: '销售额(元)',
          axisLabel: {
            formatter: '{value} 元'
          }
        },
        yAxis: {
          type: 'category',
          name:'员工姓名',
          data: this.chartData.rank.map(item => item.employee_name),
          axisLabel: {
            interval: 0,
            width: 100,
            overflow: 'truncate'
          }
        },
        series: [
          {
            type: 'bar',
            data: this.chartData.rank.map(item => ({
              name: item.customer_name,
              value: item.sales_volume
            })),
            label: {
              show: true,
              position: 'right',
              formatter: function(params) {
                const index = params.dataIndex;
                return `第${index + 1}名`;
              }
            },
            itemStyle: {
              color: function(params) {
                // 前三名使用不同颜色
                const colors = ['#FFD700', '#C0C0C0', '#CD7F32'];
                return params.dataIndex < 3 ? colors[params.dataIndex] : '#409EFF';
              }
            }
          }
        ]
      })
    }
  }
}
</script>

<style scoped lang="scss">
.chart-container {
  padding: 20px;

  .filter-card {
    margin-bottom: 20px;

    .el-date-picker, .el-select {
      width: 100%;
    }

    .el-button {
      margin-left: 10px;
    }
  }

  .data-overview {
    margin: 20px 0;
    
    .data-item {
      text-align: center;
      
      .data-title {
        font-size: 16px;
        color: #666;
        margin-bottom: 10px;
      }
      
      .data-value {
        font-size: 24px;
        font-weight: bold;
        color: #409EFF;
      }
    }
  }

  .chart-card {
    .chart {
      height: 400px;
      width: 100%;
    }
  }

  .el-card {
    margin-bottom: 20px;
  }
}
</style>